<template>
  <view class="receive-confirm-modal" v-if="visible" @click="handleMaskClick">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">收货确认</text>
        <uni-icons type="close" size="20" color="#999" @click="handleClose"></uni-icons>
      </view>
      
      <view class="modal-body">
        <!-- 物料信息 -->
        <view class="material-info-section">
          <view class="section-title">物料信息</view>
          <view class="info-grid">
            <view class="info-item">
              <text class="info-label">物料名称</text>
              <text class="info-value">{{ materialInfo.itemName || '-' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">物料编码</text>
              <text class="info-value">{{ materialInfo.itemCode || '-' }}</text>
            </view>
            <view class="info-item" v-if="materialInfo.specification">
              <text class="info-label">规格型号</text>
              <text class="info-value">{{ materialInfo.specification }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">发货数量</text>
              <text class="info-value">{{ materialInfo.quantity || 0 }} {{ materialInfo.unitName || '' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 收货仓库选择 -->
        <view class="warehouse-section">
          <view class="section-title">收货仓库</view>
          <warehouse-selector
            :warehouse-id="fixedWarehouseId"
            :warehouse-display-mode="'name'"
            :location-display-mode="'name'"
            :area-display-mode="'code'"
            :auto-open="false"
            @selected="handleWarehouseSelected"
          />
        </view>
        
        <!-- 数量输入 -->
        <view class="quantity-section">
          <view class="section-title">收货数量</view>
          <view class="quantity-inputs">
            <view class="quantity-group">
              <text class="quantity-label">收货数量</text>
              <view class="quantity-control">
                <button class="quantity-btn" @click="decreaseReceiveQuantity">-</button>
                <input 
                  class="quantity-value" 
                  v-model.number="receiveForm.actualQuantity"
                  type="number"
                  :min="0"
                  :max="maxReceiveQuantity"
                  @input="validateReceiveQuantity"
                />
                <button class="quantity-btn" @click="increaseReceiveQuantity">+</button>
              </view>
              <text class="quantity-unit">{{ materialInfo.unitName || '' }}</text>
            </view>
            
<!--            <view class="quantity-group">-->
<!--              <text class="quantity-label">拒收数量</text>-->
<!--              <view class="quantity-control">-->
<!--                <button class="quantity-btn" @click="decreaseRejectQuantity">-</button>-->
<!--                <input -->
<!--                  class="quantity-value" -->
<!--                  v-model.number="receiveForm.rejectQuantity"-->
<!--                  type="number"-->
<!--                  :min="0"-->
<!--                  :max="maxRejectQuantity"-->
<!--                  @input="validateRejectQuantity"-->
<!--                />-->
<!--                <button class="quantity-btn" @click="increaseRejectQuantity">+</button>-->
<!--              </view>-->
<!--              <text class="quantity-unit">{{ materialInfo.unitName || '' }}</text>-->
<!--            </view>-->
          </view>
          
          <!-- 数量验证提示 -->
          <view class="quantity-tip" v-if="showQuantityTip">
            <text class="tip-text">{{ quantityTipText }}</text>
          </view>
        </view>
        
      </view>
      
      <view class="modal-footer">
        <button class="modal-btn cancel-btn" @click="handleClose">取消</button>
        <button 
          class="modal-btn confirm-btn" 
          @click="handleConfirm"
          :disabled="!canConfirm"
        >
          确认收货
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import WarehouseSelector from './warehouse-selector.vue'
import { detailReceiveConfirm } from '@/api/wm/transfer.js'

export default {
  name: 'ReceiveConfirmModal',
  components: {
    WarehouseSelector
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    materialInfo: {
      type: Object,
      default: () => ({})
    },
    fixedWarehouseId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      receiveForm: {
        detailId: null,
        actualQuantity: 0,
        rejectQuantity: 0,
        inWarehouseId: null,
        inWarehouseCode: null,
        inWarehouseName: null,
        inLocationId: null,
        inLocationCode: null,
        inLocationName: null,
        inAreaId: null,
        inAreaCode: null,
        inAreaName: null
      },
      selectedWarehouse: null
    }
  },
  
  computed: {
    // 最大收货数量（发货数量）
    maxReceiveQuantity() {
      return this.materialInfo.quantity || 0
    },
    
    // 最大拒收数量（发货数量 - 收货数量）
    maxRejectQuantity() {
      return this.maxReceiveQuantity - this.receiveForm.actualQuantity
    },
    
    // 是否可以确认
    canConfirm() {
      return (this.receiveForm.actualQuantity > 0 || this.receiveForm.rejectQuantity > 0) && 
             this.selectedWarehouse && 
             (this.receiveForm.actualQuantity + this.receiveForm.rejectQuantity) <= this.maxReceiveQuantity
    },
    
    // 是否显示数量提示
    showQuantityTip() {
      return (this.receiveForm.actualQuantity + this.receiveForm.rejectQuantity) > this.maxReceiveQuantity
    },
    
    // 数量提示文本
    quantityTipText() {
      const total = this.receiveForm.actualQuantity + this.receiveForm.rejectQuantity
      const max = this.maxReceiveQuantity
      if (total > max) {
        return `收货数量 + 拒收数量不能超过发货数量 ${max}`
      }
      return ''
    }
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initForm()
      }
    }
  },
  
  methods: {
    // 初始化表单
    initForm() {
      this.receiveForm = {
        detailId: this.materialInfo.detailId,
        actualQuantity: this.materialInfo.quantity || 0, // 默认收货数量等于发货数量
        rejectQuantity: 0,
        inWarehouseId: null,
        inWarehouseCode: null,
        inWarehouseName: null,
        inLocationId: null,
        inLocationCode: null,
        inLocationName: null,
        inAreaId: null,
        inAreaCode: null,
        inAreaName: null
      }
      this.selectedWarehouse = null
    },
    
    // 处理遮罩点击
    handleMaskClick() {
      this.handleClose()
    },
    
    // 处理关闭
    handleClose() {
      this.$emit('close')
    },
    
    // 处理仓库选择
    handleWarehouseSelected(warehouseData) {
      this.selectedWarehouse = warehouseData
      this.receiveForm.inWarehouseId = warehouseData.warehouseId
      this.receiveForm.inWarehouseCode = warehouseData.warehouseCode
      this.receiveForm.inWarehouseName = warehouseData.warehouseName
      this.receiveForm.inLocationId = warehouseData.locationId
      this.receiveForm.inLocationCode = warehouseData.locationCode
      this.receiveForm.inLocationName = warehouseData.locationName
      this.receiveForm.inAreaId = warehouseData.areaId
      this.receiveForm.inAreaCode = warehouseData.areaCode
      this.receiveForm.inAreaName = warehouseData.areaName
    },
    
    // 增加收货数量
    increaseReceiveQuantity() {
      if (this.receiveForm.actualQuantity < this.maxReceiveQuantity) {
        this.receiveForm.actualQuantity++
        this.validateRejectQuantity()
      }
    },
    
    // 减少收货数量
    decreaseReceiveQuantity() {
      if (this.receiveForm.actualQuantity > 0) {
        this.receiveForm.actualQuantity--
        this.validateRejectQuantity()
      }
    },
    
    // 增加拒收数量
    increaseRejectQuantity() {
      if (this.receiveForm.rejectQuantity < this.maxRejectQuantity) {
        this.receiveForm.rejectQuantity++
      }
    },
    
    // 减少拒收数量
    decreaseRejectQuantity() {
      if (this.receiveForm.rejectQuantity > 0) {
        this.receiveForm.rejectQuantity--
      }
    },
    
    // 验证收货数量
    validateReceiveQuantity() {
      if (this.receiveForm.actualQuantity < 0) {
        this.receiveForm.actualQuantity = 0
      }
      if (this.receiveForm.actualQuantity > this.maxReceiveQuantity) {
        this.receiveForm.actualQuantity = this.maxReceiveQuantity
      }
      this.validateRejectQuantity()
    },
    
    // 验证拒收数量
    validateRejectQuantity() {
      const maxReject = this.maxReceiveQuantity - this.receiveForm.actualQuantity
      if (this.receiveForm.rejectQuantity > maxReject) {
        this.receiveForm.rejectQuantity = maxReject
      }
      if (this.receiveForm.rejectQuantity < 0) {
        this.receiveForm.rejectQuantity = 0
      }
    },
    
    // 处理确认
    handleConfirm() {
      if (!this.canConfirm) {
        uni.showToast({ title: '请完善收货信息', icon: 'none' })
        return
      }
      
      // 验证数量
      if (this.receiveForm.actualQuantity < 0) {
        uni.showToast({ title: '收货数量必须大于等于0', icon: 'none' })
        return
      }
      
      if ((this.receiveForm.actualQuantity + this.receiveForm.rejectQuantity) > this.maxReceiveQuantity) {
        uni.showToast({ title: '收货数量 + 拒收数量不能超过发货数量', icon: 'none' })
        return
      }
      
      // 调用收货确认接口
      this.executeReceiveConfirm()
    },
    
    // 执行收货确认
    executeReceiveConfirm() {
      uni.showLoading({ title: '收货中...' })
      
      detailReceiveConfirm({ ...this.receiveForm }).then(response => {
        uni.showToast({ 
          title: '收货确认成功', 
          icon: 'success',
          duration: 2000
        })
        
        // 关闭弹窗
        this.handleClose()
        
        // 通知父组件刷新数据
        this.$emit('success')
        
      }).catch(error => {
        // code=500等业务错误和网络异常都会进入这里
        console.log('收货确认失败:', error)
        
        // 检查是否是业务错误（code=500）
        if (error === '500') {
          // 拦截器已经显示了具体的业务错误信息，这里不需要再显示
          console.log('业务错误，拦截器已显示toast')
        } else {
          // 真正的网络异常
          uni.showToast({ 
            title: '网络异常，请检查网络连接后重试', 
            icon: 'none',
            duration: 3000
          })
        }
      }).finally(() => {
        uni.hideLoading()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.receive-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  
  .modal-content {
    width: 90%;
    max-width: 600rpx;
    max-height: 85vh;
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    background: #f8f9fa;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .modal-body {
    flex: 1;
    padding: 30rpx;
    overflow-y: auto;
  }
  
  .modal-footer {
    display: flex;
    gap: 20rpx;
    padding: 30rpx;
    border-top: 1rpx solid #eee;
    background: #f8f9fa;
    
    .modal-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      border: none;
      font-size: 28rpx;
      font-weight: bold;
      
      &.cancel-btn {
        background: #f8f9fa;
        color: #666;
        border: 1rpx solid #ddd;
      }
      
      &.confirm-btn {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: #fff;
        
        &:disabled {
          background: #ccc;
          color: #999;
        }
      }
    }
  }
}

.material-info-section, .warehouse-section, .quantity-section {
  margin-bottom: 40rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    padding-bottom: 10rpx;
    border-bottom: 2rpx solid #28a745;
  }
}

.material-info-section {
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20rpx;
    
    .info-item {
      display: flex;
      flex-direction: column;
      
      .info-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      .info-value {
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

.quantity-section {
  .quantity-inputs {
    display: flex;
    flex-direction: column;
    gap: 30rpx;
    
    .quantity-group {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .quantity-label {
        font-size: 26rpx;
        color: #333;
        min-width: 120rpx;
        font-weight: 500;
      }
      
      .quantity-control {
        display: flex;
        align-items: center;
        gap: 10rpx;
        
        .quantity-btn {
          width: 60rpx;
          height: 60rpx;
          border: 1rpx solid #28a745;
          border-radius: 8rpx;
          background: #fff;
          font-size: 28rpx;
          font-weight: bold;
          color: #28a745;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:active {
            background: #f0f8f0;
          }
        }
        
        .quantity-value {
          width: 120rpx;
          height: 60rpx;
          text-align: center;
          border: 1rpx solid #28a745;
          border-radius: 8rpx;
          font-size: 26rpx;
          background: #f8f9fa;
          
          &:focus {
            background: #fff;
          }
        }
      }
      
      .quantity-unit {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
  
  .quantity-tip {
    margin-top: 20rpx;
    padding: 15rpx;
    background: #fff3cd;
    border: 1rpx solid #ffeaa7;
    border-radius: 8rpx;
    
    .tip-text {
      font-size: 24rpx;
      color: #856404;
    }
  }
}

</style>
